package com.yuanli.cosmeticmirror.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;

import com.cgfay.filter.glfilter.resource.FilterHelper;
import com.comenjoysoft.baselibrary.util.SPUtils;
import com.comenjoysoft.baselibrary.util.ThreadUtils;
import com.kongzue.dialog.v3.CustomDialog;
import com.umeng.commonsdk.debug.I;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.rxjava.rxlife.RxLife;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.model.iview.IwelcomeView;
import com.yuanli.cosmeticmirror.persenter.WelcomePersenter;
import com.zrq.spanbuilder.Spans;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

import static com.yuanli.cosmeticmirror.base.Constant.USER_AGREEMENT_PRIVACY_POLICY;

public class WelcomeActivity extends BaseActivity implements IwelcomeView {

    private WelcomePersenter persenter;

    @Override
    protected int getContentView() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void init(Bundle bundle) {
        persenter = new WelcomePersenter(this, this);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        boolean isRead = SPUtils.getInstance().getBoolean(Constant.SP_USER_AGREEMENT_REMINDS_AGAIN, false);
        if (isRead) {
            show();
        } else {
            getCustomDialog();
        }
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                FilterHelper.initAssetsFilter(WelcomeActivity.this);
                return null;
            }

            @Override
            public void onSuccess(Object result) {
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFail(Throwable t) {
            }
        });


    }

    private void show() {
        boolean isFisrt = SPUtils.getInstance().getBoolean(Constant.IS_FIRST_LOGIN, false);
        String userName = SPUtils.getInstance().getString(Constant.SP_USER_ACCOUNT, "");
        String password = SPUtils.getInstance().getString(Constant.SP_USER_PASSWORD, "");
        new RxPermissions(this)
                .request(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribeOn(Schedulers.io())
                .as(RxLife.asOnMain(this))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Observable.timer(2, TimeUnit.SECONDS)
                                .as(RxLife.as(WelcomeActivity.this))
                                .subscribe(aLong -> {
                                    login(isFisrt, userName, password);
                                });
                    } else {
                        showToast("请求权限失败");
                        appManager.AppExit(WelcomeActivity.this);
                    }
                });
    }

    private void login(boolean isFirst, String userName, String password) {
        if (isFirst) {
            if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                finish();
                persenter.firstRunApp();
                persenter.firsOpen();
                persenter.firsLogin();
                return;
            }

            startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
            finish();
        } else {
            persenter.firstRunAppNew();
            startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
            finish();
        }
    }

    @Override
    protected void destroy() {

    }

    /**
     * 用户协议/隐私政策
     *
     * @return
     */
    private void getCustomDialog() {
        CustomDialog.show(this, R.layout.dialog_welcome, (dialog, view) -> {
            AppCompatCheckBox welcomeCb = view.findViewById(R.id.welcome_cb);

            TextView welcomeUserAgreement = view.findViewById(R.id.welcome_user_agreement);
            TextView welcomePrivacyPolicy = view.findViewById(R.id.welcome_privacy_policy);
            welcomeUserAgreement.setOnClickListener(v1 -> toAgreement(1));
            welcomePrivacyPolicy.setOnClickListener(v1 -> toAgreement(2));

            view.findViewById(R.id.welcome_enter).setOnClickListener(v1 -> {
                dialog.doDismiss();
                SPUtils.getInstance().put(Constant.SP_USER_AGREEMENT_REMINDS_AGAIN, welcomeCb.isChecked());
                show();
            });

            view.findViewById(R.id.welcome_cancel).setOnClickListener(v1 -> {
                dialog.doDismiss();
                showDialog2();
            });
        }).setAlign(CustomDialog.ALIGN.DEFAULT);
    }


    private void showDialog2(){
        String appName = getString(R.string.app_name);
        String content = getStr(R.string.welcome_hint, appName);
        CustomDialog.show(this, R.layout.dialog_welcome2, (dialog, view) -> {
            TextView tvContent1 = view.findViewById(R.id.tv_content_1);
            tvContent1.setText(content);

            TextView tvContent2 = view.findViewById(R.id.tv_content_2);
            tvContent2.setText(setContent(tvContent2));

            view.findViewById(R.id.welcome_enter).setOnClickListener(v1 -> {
                dialog.doDismiss();
                show();
            });

            view.findViewById(R.id.welcome_cancel).setOnClickListener(v1 -> {
                dialog.doDismiss();
                appManager.AppExit(WelcomeActivity.this);
            });

        }).setCancelable(false).setAlign(CustomDialog.ALIGN.DEFAULT);
    }

    private String getStr(int strId, String appName){
        return appName != null ?
                getString(strId, appName) :
                getString(strId);
    }


    private Spans setContent(TextView tvContent2){
        int colorId = Color.parseColor("#ff4f78");
        return Spans.builder()
                .text("您可以通过阅读")
                .text("《用户协议》").color(colorId).click(tvContent2, new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        toAgreement(1);
                    }
                }).underLine()
                .text("和")
                .text("《隐私政策》").color(colorId).click(tvContent2, new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        toAgreement(2);
                    }
                }).underLine()
                .text("来了解详细信息")
                .build();
    }


    /**
     * 前往用户协议界面
     * @param code 1：用户协议，2：隐私政策
     */
    private void toAgreement(int code){
        Intent intent = new Intent(WelcomeActivity.this, ProtocolActivity.class);
        intent.putExtra(USER_AGREEMENT_PRIVACY_POLICY, code);
        startActivity(intent);
    }
}
